package com.code.common.utils;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.core.publisher.Mono;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: Yan
 * @date: 2022/10/14
 */
public class HelperUtil {

    public static Map<String, Object> encapsulateRequestArgs() {
        return encapsulateRequestArgs(getHttpServletRequest());
    }

    /**
     * 解析请求的参数封装为 map
     * @param request
     * @return
     */
    public static Map<String, Object> encapsulateRequestArgs(ServletRequest request){
        Map<String, Object> argsMap = new HashMap<>(8);
        Enumeration<String> names = request.getParameterNames();

        while (names.hasMoreElements()){
            String elementName = names.nextElement();
            String[] values = request.getParameterValues(elementName);
            if (ArrayUtil.isNotEmpty(values)){
                if (values.length == 1){
                    argsMap.put(elementName, values[0]);
                }else {
                    argsMap.put(elementName, ListUtil.toList(values));
                }
            }
        }

        return argsMap;
    }

    public static HttpServletRequest getHttpServletRequest(){
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    /**
     * 基本 response 返回
     * @param response
     * @param data
     * @throws IOException
     */
    public static void httpOutput(HttpServletResponse response, Object data) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(data));
        writer.flush();
        writer.close();
    }

    /**
     * 基于 webflux 的 response 返回
     * @param response
     * @param data
     * @return
     */
    public static Mono<Void> httpMonoOutput(ServerHttpResponse response, Object data){
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String body = JSONUtil.toJsonStr(data);
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
        return response.writeWith(Mono.just(buffer));
    }
}
